import { createElement } from 'react';
import dynamic from 'dva/dynamic';
import { getMenuData } from './menu';

let routerDataCache;

// const modelNotExisted = (app, model) => (
//   !app._models.some(({ namespace }) => {
//     return namespace === model.substring(model.lastIndexOf('/') + 1);
//   })
// );

// wrapper of dynamic
const dynamicWrapper = (app, models, component) => {
  // () => require('module')
  // transformed by babel-plugin-dynamic-import-node-sync
  if (component.toString().indexOf('.then(') < 0) {
    models.forEach((model) => {
      // if (modelNotExisted(app, model)) {
      //   console.log(model)
      //   app.model(require(model).default);
      // }
      app.model(model().default);
    });
    return (props) => {
      if (!routerDataCache) {
        routerDataCache = getRouterData(app);
      }
      return createElement(component().default, {
        ...props,
        routerData: routerDataCache,
      });
    };
  }
  // () => import('module')
  return dynamic({
    app,
    // models: () => models.filter(
    //   model => modelNotExisted(app, model)).map(m => import(m)
    // ),
    models: () => models.map((m) => {
      return m();
    }),
    // add routerData prop
    component: () => {
      if (!routerDataCache) {
        routerDataCache = getRouterData(app);
      }
      return component().then((raw) => {
        const Component = raw.default || raw;
        return props => createElement(Component, {
          ...props,
          routerData: routerDataCache,
        });
      });
    },
  });
};

function getFlatMenuData(menus) {
  let keys = {};
  menus.forEach((item) => {
    if (item.children) {
      keys[item.path] = { ...item };
      keys = { ...keys, ...getFlatMenuData(item.children) };
    } else {
      keys[item.path] = { ...item };
    }
  });
  return keys;
}

export const getRouterData = (app) => {
  const routerConfig = {
    '/': {
      component: dynamicWrapper(app, [], () => import('../layouts')),
    },
    '/home': {
      component: dynamicWrapper(app, [], () => import('../routes/Home')),
    },
    // '/dashboard/analysis': {
    //   component: dynamicWrapper(app, [() => import('../routes/Dashboard/models/chart')], () => import('../routes/Dashboard/Analysis')),
    // },
    // '/dashboard/monitor': {
    //   component: dynamicWrapper(app, ['../routes/Dashboard/models/monitor'], () => import('../routes/Dashboard/Monitor')),
    // },
    // '/dashboard/workplace': {
    //   component: dynamicWrapper(app, ['../routes/Dashboard/models/project', '../routes/Dashboard/models/activities', '../routes/Dashboard/models/chart'], () => import('../routes/Dashboard/Workplace')),
    // },
    // '/form/basic-form': {
    //   component: dynamicWrapper(app, [() => import('../routes/Forms/form')], () => import('../routes/Forms/BasicForm')),
    // },
    // '/form/step-form': {
    //   component: dynamicWrapper(app, [() => import('../routes/Forms/form')], () => import('../routes/Forms/StepForm')),
    // },
    // '/form/step-form/info': {
    //   component: dynamicWrapper(app, [() => import('../routes/Forms/form')], () => import('../routes/Forms/StepForm/Step1')),
    // },
    // '/form/step-form/confirm': {
    //   component: dynamicWrapper(app, [() => import('../routes/Forms/form')], () => import('../routes/Forms/StepForm/Step2')),
    // },
    // '/form/step-form/result': {
    //   component: dynamicWrapper(app, [() => import('../routes/Forms/form')], () => import('../routes/Forms/StepForm/Step3')),
    // },
    // '/form/advanced-form': {
    //   component: dynamicWrapper(app, [() => import('../routes/Forms/form')], () => import('../routes/Forms/AdvancedForm')),
    // },
    // '/list/table-list': {
    //   component: dynamicWrapper(app, [() => import('../routes/List/models/rule')], () => import('../routes/List/TableList')),
    // },
    // '/list/basic-list': {
    //   component: dynamicWrapper(app, [() => import('../routes/List/models/list')], () => import('../routes/List/BasicList')),
    // },
    // '/list/card-list': {
    //   component: dynamicWrapper(app, [() => import('../routes/List/models/list')], () => import('../routes/List/CardList')),
    // },
    // '/list/search': {
    //   component: dynamicWrapper(app, [() => import('../routes/List/models/list')], () => import('../routes/List/List')),
    // },
    // '/list/search/projects': {
    //   component: dynamicWrapper(app, [() => import('../routes/List/models/list')], () => import('../routes/List/Projects')),
    // },
    // '/list/search/applications': {
    //   component: dynamicWrapper(app, [() => import('../routes/List/models/list')], () => import('../routes/List/Applications')),
    // },
    // '/list/search/articles': {
    //   component: dynamicWrapper(app, [() => import('../routes/List/models/list')], () => import('../routes/List/Articles')),
    // },
    // '/profile/basic': {
    //   component: dynamicWrapper(app, [() => import('../routes/Profile/profile')], () => import('../routes/Profile/BasicProfile')),
    // },
    // '/profile/advanced': {
    //   component: dynamicWrapper(app, [() => import('../routes/Profile/profile')], () => import('../routes/Profile/AdvancedProfile')),
    // },
    '/result/success': {
      component: dynamicWrapper(app, [], () => import('../routes/Result/Success')),
    },
    '/result/fail': {
      component: dynamicWrapper(app, [], () => import('../routes/Result/Error')),
    },
    '/exception/403': {
      component: dynamicWrapper(app, [], () => import('../routes/Exception/403')),
    },
    '/exception/404': {
      component: dynamicWrapper(app, [], () => import('../routes/Exception/404')),
    },
    '/exception/500': {
      component: dynamicWrapper(app, [], () => import('../routes/Exception/500')),
    },
    '/blank': {
      component: dynamicWrapper(app, [], () => import('../layouts/BlankLayout')),
    },
    '/blank/nosupport': {
      component: dynamicWrapper(app, [], () => import('../routes/Exception/nosupport')),
    },
    '/user': {
      component: dynamicWrapper(app, [], () => import('../layouts/UserLayout')),
    },
    '/user/login': {
      component: dynamicWrapper(app, [], () => import('../routes/User/Login')),
    },
    '/user/register': {
      component: dynamicWrapper(app, [], () => import('../routes/User/Register')),
    },
    '/user/register-result': {
      component: dynamicWrapper(app, [], () => import('../routes/User/RegisterResult')),
    },
    // '/user/:id': {
    //   component: dynamicWrapper(app, [], () => import('../routes/User/SomeComponent')),
    // },

    //系统管理路由
    // '/admin': {
    //   component: dynamicWrapper(app, [], () => import('../routes/Admin')),
    // },
    '/admin/role': {
      component: dynamicWrapper(app, [() => import('../routes/Admin/Role/role')], () => import('../routes/Admin/Role')),
    },
    '/admin/user': {
      component: dynamicWrapper(app, [() => import('../routes/Admin/User/user')], () => import('../routes/Admin/User')),
    },
    '/admin/organ': {
      component: dynamicWrapper(app, [() => import('../routes/Admin/Organ/organ')], () => import('../routes/Admin/Organ')),
    },
    '/admin/resource': {
      component: dynamicWrapper(app, [() => import('../routes/Admin/Resource/resource')], () => import('../routes/Admin/Resource')),
    },
    '/admin/permission': {
      component: dynamicWrapper(app, [() => import('../routes/Admin/Permission/permission')], () => import('../routes/Admin/Permission')),
    },
    '/admin/session': {
      component: dynamicWrapper(app, [() => import('../routes/Admin/Session/session')], () => import('../routes/Admin/Session')),
    },
    '/admin/dic': {
      component: dynamicWrapper(app, [() => import('../routes/Admin/Dic/dic')], () => import('../routes/Admin/Dic')),
    },
    '/admin/cache': {
      component: dynamicWrapper(app, [() => import('../routes/Admin/Cache/cache')], () => import('../routes/Admin/Cache')),
    },
    '/admin/opinion': {
      component: dynamicWrapper(app, [() => import('../routes/Admin/Opinion/opinion')], () => import('../routes/Admin/Opinion')),
    },
    '/admin/file': {
      component: dynamicWrapper(app, [() => import('../routes/Admin/File/file')], () => import('../routes/Admin/File')),
    },
    '/admin/system': {
      component: dynamicWrapper(app, [() => import('../routes/Admin/System/model')], () => import('../routes/Admin/System')),
    },
    // '/admin/test': {
    //   component: dynamicWrapper(app, [], () => import('../routes/Admin/Test')),
    // },

    //日志管理路由
    '/logger/sysLog': {
      component: dynamicWrapper(app, [() => import('../routes/Logger/SysLog/sysLog')], () => import('../routes/Logger/SysLog')),
    },
    '/logger/modifyInfo': {
      component: dynamicWrapper(app, [() => import('../routes/Logger/ModifyInfo/modifyInfo')], () => import('../routes/Logger/ModifyInfo')),
    },
    '/logger/event': {
      component: dynamicWrapper(app, [() => import('../routes/Logger/Event/event')], () => import('../routes/Logger/Event')),
    },
    '/logger/loginLog': {
      component: dynamicWrapper(app, [() => import('../routes/Logger/LoginLog/loginLog')], () => import('../routes/Logger/LoginLog')),
    },
    //博客
    '/blog/article': {
      component: dynamicWrapper(app, [() => import('../routes/Blog/Article/article')], () => import('../routes/Blog/Article')),
    },
    '/blog/classification': {
      component: dynamicWrapper(app, [() => import('../routes/Blog/Classification/classification')], () => import('../routes/Blog/Classification')),
    },
    '/blog/issue': {
      component: dynamicWrapper(app, [() => import('../routes/Blog/Article/article')], () => import('../routes/Blog/Article/issue')),
    },

    //其他
    '/other/dragact': {
      component: dynamicWrapper(app, [], () => import('../routes/Other/Dragact')),
    },

    //系统设置
    '/account/settings': {
      component: dynamicWrapper(app, [() => import('../models/geographic')], () => import('../routes/Account/Settings/Info')),
    },
    '/account/settings/base': {
      component: dynamicWrapper(app, [() => import('../models/geographic')], () => import('../routes/Account/Settings/BaseView')),
    },
    '/account/settings/security': {
      component: dynamicWrapper(app, [() => import('../models/geographic')], () => import('../routes/Account/Settings/SecurityView')),
    },
    '/account/settings/binding': {
      component: dynamicWrapper(app, [() => import('../models/geographic')], () => import('../routes/Account/Settings/BindingView')),
    },
    '/account/settings/notification': {
      component: dynamicWrapper(app, [() => import('../models/geographic')], () => import('../routes/Account/Settings/NotificationView')),
    },


    //工作流
    '/workflow/leave': {
      component: dynamicWrapper(app, [() => import('../routes/Workflow/Leave/leave')], () => import('../routes/Workflow/Leave')),
    },
    //工作流
    '/workflow/task': {
      component: dynamicWrapper(app, [() => import('../routes/Workflow/Task/task')], () => import('../routes/Workflow/Task')),
    },
    '/workflow/expenseAccount': {
      component: dynamicWrapper(app, [() => import('../routes/Workflow/ExpenseAccount/expenseAccount')], () => import('../routes/Workflow/ExpenseAccount')),
    },
    '/workflow/salary/employeeSalary': {
      component: dynamicWrapper(app, [() => import('../routes/Workflow/EmployeeSalary/employeeSalary')], () => import('../routes/Workflow/EmployeeSalary')),
    },
    '/workflow/salary/salaryAdjust': {
      component: dynamicWrapper(app, [() => import('../routes/Workflow/SalaryAdjust/model')], () => import('../routes/Workflow/SalaryAdjust')),
    },
  };
  // Get name from ./menu.js or just set it in the router data.
  const menuData = getFlatMenuData(getMenuData());
  const routerData = {};
  Object.keys(routerConfig).forEach((item) => {
    const menuItem = menuData[item.replace(/^\//, '')] || {};
    routerData[item] = {
      ...routerConfig[item],
      name: routerConfig[item].name || menuItem.name,
    };
  });
  return routerData;
};
